import { useCallback, useEffect, useState } from 'react'
import { useRecoilValue } from 'recoil'
import { throttle } from 'lodash'
import { theQuarterData } from '@/store/user'
import { HomeHooksData, TableInfo } from '../data'
import { isNullArray, isNullData } from '@/utils'
import { getTableList } from '../service'

export default (): HomeHooksData => {
  const quarterData = useRecoilValue(theQuarterData)

  // 当前选中任务
  const [task, setTask] = useState<Array<string>>(
    isNullArray(quarterData) ? [quarterData[0].value, quarterData![0].children![0].value] : [],
  )

  const [tableList, setTableList] = useState<TableInfo[]>([])

  const [loading, setLoading] = useState<boolean>(false)
  // 任务下拉框变化时触发
  const handleTaskChange = (e: Array<string>) => {
    setTask(e)
  }

  // 加载首页数据
  const getTables = useCallback(async () => {
    setLoading(true)
    const res = await getTableList({
      year: task[0] ? task[0] : '',
      quarter: task[1] ? task[1] : '',
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setTableList(res.data)
    } else {
      setTableList([])
    }
    setLoading(false)
  }, [task])

  const searchData = useCallback(
    throttle(() => {
      getTables()
    }, 1000),
    [task],
  )

  // 重置
  const resetData = useCallback(
    throttle(() => {
      setTask([])
    }, 1000),
    [],
  )

  useEffect(() => {
    if (!isNullArray(task)) {
      searchData()
    }
    return () => {
      searchData.cancel()
    }
  }, [task])

  useEffect(() => {
    getTables()
  }, [])

  return {
    task,
    resetData,
    handleTaskChange,
    getTables,
    tableList,
    loading,
    searchData,
  }
}
